<?php
/**
 * api参数定义
 * User: 13651
 * Time: 2025/9/11 10:05
 */

namespace App\Param;

use App\Common\ResponseCode;
use App\Exceptions\BusinessException;
use Illuminate\Support\Facades\Validator;

class Param
{

    /**
     * 获取校验对象
     * @return mixed
     */
    public static function create()
    {
        return (new static())->fill();
    }

    /**
     * 动态赋值
     * @param bool $sign
     * @return $this
     * @throws BusinessException
     */
    protected function fill(bool $sign = false)
    {
        $rules = $this->rules();
        // 获取所有参数
        $data = $sign ? request()->input('data', []) : request()->input();
        // 校验参数
        $validator = Validator::make($data, $rules,$this->message());
        if($validator->fails()) {
            $validatorMsg = $validator->getMessageBag()->getMessages();
            $errorMsg = $validatorMsg[array_keys($validatorMsg)[0]][0];
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL);
        }
        // 动态赋值
        collect($data)->map(function ($val, $key) {
            if(property_exists($this, $key)) {
                $this->{$key} = $val;
            }
        });

        return $this;
    }

    /**
     * 参数校验规则
     *
     * @return array
     */
    public function rules()
    {
        return [];
    }

    public function message()
    {
        return [
        ];
    }

    /**
     * 转换为数组
     * @return array
     */
    public function toArray()
    {
        $arr = [];
        foreach ($this as $field => $value) {
            if(property_exists($this, $field)) {
                $arr[$field] = $value;
            }
        }
        return $arr;
    }
}